package com.example.weather.client;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.example.weather.config.WeatherProperties;
import com.example.weather.contant.WeatherContant;
import com.example.weather.contant.WeatherParam;
import com.example.weather.pojo.WeatherResponse;
import com.example.weather.pojo.WeatherVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.IOException;


@Slf4j
@Component
public class WeatherClient {
    @Autowired
    private  WeatherProperties weatherProperties;


    public WeatherVo getWeather(String adCode) {
        WeatherVo vo = new WeatherVo();
        //预报
        String forecastUrl = getUrl(adCode, WeatherParam.EXTENSIONS_ALL);
        WeatherResponse weatherForecastResponse= sendWeatherDate(forecastUrl);
        if (ObjectUtil.isNotEmpty(weatherForecastResponse)&&weatherForecastResponse.getStatus()==1){
            vo.setForecasts(weatherForecastResponse.getForecasts());
        }
        //实况
        String liveUrl = getUrl(adCode, WeatherParam.EXTENSIONS_BASE);
        WeatherResponse weatherLiveResponse= sendWeatherDate(liveUrl);
        if (ObjectUtil.isNotEmpty(weatherLiveResponse)&&weatherLiveResponse.getStatus()==1){
            vo.setLives(weatherLiveResponse.getLives());
        }
        return vo;
    }
    public  WeatherResponse sendWeatherDate(String url) {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        try {
            int code = httpClient.executeMethod(getMethod);
            if (code == 200){
                String responseBodyAsString = getMethod.getResponseBodyAsString();
                log.info("responseBodyAsString,{}",responseBodyAsString);
                WeatherResponse bean = JSONUtil.toBean(responseBodyAsString, WeatherResponse.class);
                return bean;
            }else {
                log.error("请求失败");
            }
        } catch (IOException e) {
            log.error("请求失败");
        }
        return null;
    }
    public String getUrl(String adCode,String extensions){
        String param = WeatherContant.CITY +adCode+WeatherContant.EXTENSIONS+extensions +WeatherContant.KEY+ weatherProperties.getKey()+WeatherContant.OUTPUT+weatherProperties.getOutput();
        System.err.println(param);
        String url = WeatherContant.URL+param;
        // md5加密得到签名(参数和秘钥）
        String md5 = DigestUtils.md5DigestAsHex((param + weatherProperties.getSig()).getBytes());
        url=url+WeatherContant.SIG+md5;
        return url;
    }
}
